package action;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import bean.user.SessionUser;

import dm.ShoppingDM;
import gate.ActionHandler;

public class ActionShopping implements ActionHandler {

	@Override
	public void handleAction(HttpServletRequest req, HttpServletResponse res) {
	try {
		ShoppingDM dm = new ShoppingDM();
		String url = req.getParameter("URL");
		String action = req.getParameter("actionType");
		
		if(action.equals("ADD_PRODUCT")){
			
			try {
				int productId = Integer.parseInt(req.getParameter("productId"));
				int count = Integer.parseInt(req.getParameter("count"));
				HttpSession s = req.getSession();
				SessionUser user = (SessionUser) s.getAttribute("user");
				
				dm.addProduct(productId, count, user.getUserId());
			} catch (Exception e) {
				req.setAttribute("error", "Error !"+e.getMessage());
			}
			
		}else if(action.equals("REMOVE_PRODUCT")){
			
			try {
				int id = Integer.parseInt(req.getParameter("id"));
				
				HttpSession s = req.getSession();
				SessionUser user = (SessionUser) s.getAttribute("user");
				dm.removeProduct(id, user.getUserId());
			} catch (Exception e) {
				req.setAttribute("error", "Error !"+e.getMessage());
			}
			
		}else if(action.equals("UPDATE_PRODUCT")){
			try {
				int id = Integer.parseInt(req.getParameter("id"));
				int count = Integer.parseInt(req.getParameter("count"));
				HttpSession s = req.getSession();
				SessionUser user = (SessionUser) s.getAttribute("user");
				
				dm.updateProduct(id, count, user.getUserId());
			} catch (Exception e) {
				req.setAttribute("error", "Error !"+e.getMessage());
			}
			
		}else{
			req.setAttribute("error", "Action not found !");
		}
		
		req.getRequestDispatcher(url).forward(req, res);
		} catch (ServletException e) {
			e.printStackTrace();
	} catch (IOException e) {
		e.printStackTrace();
	}
	}
}

	
